package pers.hl.module_main.publish

import com.amap.api.maps2d.model.LatLng
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import pers.hl.common.base.BaseViewModel
import pers.hl.common.base.SingleLiveEvent
import pers.hl.lib_global.http.DouBanErrorResponse
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.BookTag
import pers.hl.lib_global.model.bean.DoubanBook
import pers.hl.lib_global.model.bean.Library

class PublishViewModel: BaseViewModel<PublishModel>() {

    fun getAllTags(): SingleLiveEvent<List<BookTag>> {
        return createSimpleEvent {
            val result = mModel.getAllTags()
            result.data
        }
    }

    fun publishBook(book: Book): SingleLiveEvent<String> {
        return createSimpleEvent {
            val result = mModel.addBook(book)
            result.msg
        }
    }

    fun fetchNearByLibraries(curPos: LatLng): SingleLiveEvent<List<Library>> {
        return createSimpleEvent {
            val result = mModel.fetchNearByLibraries(curPos)
            result.data
        }
    }

    /**
     * 根据isbn获取豆瓣图书信息
     */
    fun fetchDouBanInfo(isbnCode: Long): SingleLiveEvent<DoubanBook> {
        val event = createSingleLiveEvent<DoubanBook>()
        launchOnIO {
           val result = mModel.getDoubanBook(isbnCode)
            val data = result.data
            if (data is DouBanErrorResponse) {
                LogUtils.e("数据错误，$data")
                event.postValue(null)
            } else {
                val doubanBook = GsonUtils.fromJson(data as String, DoubanBook::class.java)
                event.postValue(doubanBook)
            }
        }
        return event
    }

    fun getAllLibraries(): SingleLiveEvent<List<Library>> {
        return createSimpleEvent {
            val result = mModel.getAllLibraries()
            result.data
        }
    }

}